package session.stateless;

import entity.Address;
import entity.Credit;
import entity.Customer;


import entity.Employee;
import entity.Employee;
import entity.Inquiry;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

@Stateless
public class CustomerSessionBean implements CustomerSessionBeanLocal, CustomerSessionBeanRemote {

    @PersistenceContext
    private EntityManager entityManager;
    @EJB
    SalesInquirySessionBeanLocal salesInquirySessionBeanLocal;

    @Override
    public void addCustomer(String userId, String email, String firstName, String lastName, String company, String title, String status, Integer phone, Address companyAddress, Double revenue, String description,
            Integer numEmployee, String industry, ArrayList<Address> addresses, String type, Boolean assigned, List<Inquiry> inquiries) {

        Address cAddress = new Address(companyAddress.getStreet(), companyAddress.getCountry(), companyAddress.getCity(), companyAddress.getPostal(), "Company");

        Employee e = entityManager.find(Employee.class, userId);

        Customer customer;
        ArrayList<Address> addresseslist = new ArrayList<Address>();
        if (addresses != null) {
//            ArrayList<Address> addresseslist = new ArrayList<Address>();
            for (Address s : addresses) {
                Address temp = new Address(s.getStreet(), s.getCountry(), s.getCity(), s.getPostal(), s.getType());
                addresseslist.add(temp);
            }

            System.out.println("addresseslist.size(): " + addresseslist.size());

            customer = new Customer(e, email, firstName, lastName, company, title, status, phone, cAddress, revenue, description, numEmployee, industry, addresseslist, type, assigned);


        } else {
            customer = new Customer(e, email, firstName, lastName, company, title, status, phone, cAddress, revenue, description, numEmployee, industry, addresseslist, type, assigned);
        }
        if (inquiries != null) {
            List<Inquiry> inquiriesList = new ArrayList<Inquiry>();
            for (Inquiry i : inquiries) {
                inquiriesList.add(salesInquirySessionBeanLocal.getInquiry(i.getId()));
            }

            customer.setInquiries(inquiriesList);
        }

        customer.setCredit(null);

        entityManager.persist(customer);
        entityManager.flush();

        customer = getCustomerByCompany(company);

        System.out.println("customer: " + customer);
    }

    @Override
    public ArrayList<Customer> getCustomers() {
        Query query = entityManager.createQuery("SELECT u FROM Customer u");

        ArrayList<Customer> al = new ArrayList<Customer>();

        for (Object o : query.getResultList()) {
            Customer l = (Customer) o;
            al.add(l);
        }

        return al;
    }

    @Override
    public ArrayList<Customer> getCustomers(Boolean type, int action) {
        Query query = entityManager.createQuery("SELECT u FROM Customer u");

        ArrayList<Customer> al = new ArrayList<Customer>();

        if (action == 1) {
            for (Object o : query.getResultList()) {
                Customer l = (Customer) o;
                if (l.getAssigned().equals(type)) {
                    al.add(l);
                }
            }
        } else if (action == 2) { //get customers for finance
            if (type == false) { //to add credit rating
                for (Object o : query.getResultList()) {
                    Customer l = (Customer) o;
                    if (l.getCredit() == null) {
                        al.add(l);
                    }
                }
            } else { //to update credit rating
                for (Object o : query.getResultList()) {
                    Customer l = (Customer) o;
                    if (l.getCredit() != null) {
                        al.add(l);
                    }
                }
            }
        }

        return al;
    }

    @Override
    public ArrayList<Customer> getCustomers(String userId) {
        Query query = entityManager.createQuery("SELECT u FROM Customer u");
        ArrayList<Customer> al = new ArrayList<Customer>();
        for (Object o : query.getResultList()) {
            Customer l = (Customer) o;
            if (l.getAssigned()) {
                if (l.getEmployee().getUserId().compareTo(userId) == 0) {
                    al.add(l);
                }
            }
        }

        return al;
    }

    @Override
    public Customer getCustomer(Long custId) {
        Customer customer = entityManager.find(Customer.class, custId);

        return customer;
    }

    @Override
    public Customer getCustomerByCompany(String company) {
        Query query = entityManager.createQuery("SELECT c FROM Customer c");

        for (Object o : query.getResultList()) {
            Customer c = (Customer) o;

            if (c.getCompany().equals(company)) {
                return c;
            }
        }

        return null;
    }

    @Override
    public Customer getCustomerByEmail(String email) {
        Query query = entityManager.createQuery("SELECT c FROM Customer c");

        for (Object o : query.getResultList()) {
            Customer c = (Customer) o;

            if (c.getEmail().equals(email)) {
                return c;
            }
        }

        return null;
    }

    @Override
    public Customer getCustomer(String email, Boolean t) {
        Query query = entityManager.createQuery("SELECT u FROM Customer u WHERE u.email = :inemail");
        query.setParameter("inemail", email);
        Customer customer = null;

        try {
            customer = (Customer) query.getSingleResult();
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return customer;
    }

    @Override
    public void updateCustomer(Long custId, String userId, String email, String firstName, String lastName, String company, String title, String status, Integer phone, Address companyAddress, Double revenue, String description,
            Integer numEmployee, String industry, ArrayList<Address> addresses, String type, Boolean assigned) {
        try {
            Customer customer = entityManager.find(Customer.class, custId);

            if (customer != null) {
                Employee employee = entityManager.find(Employee.class, userId);
                customer.setEmployee(employee);
                customer.setEmail(email);
                customer.setFirstName(firstName);
                customer.setLastName(lastName);
                customer.setCompany(company);
                customer.setTitle(title);
                customer.setStatus(status);
                customer.setPhone(phone);
                Address address = customer.getCompanyAddress();
                address.setStreet(companyAddress.getStreet());
                address.setCountry(companyAddress.getCountry());
                address.setCity(companyAddress.getCity());
                address.setPostal(companyAddress.getPostal());


                Collection<Address> addresseslist = new ArrayList<Address>();

                for (Address s : addresses) {
                    Address temp = new Address(s.getStreet(), s.getCountry(), s.getCity(), s.getPostal(), s.getType());
                    addresseslist.add(temp);
                }
                customer.setAddresses(addresseslist);
                customer.setCompanyAddress(address);
                customer.setRevenue(revenue);
                customer.setDescription(description);
                customer.setNumEmployee(numEmployee);
                customer.setIndustry(industry);
                customer.setAssigned(assigned);
            }

            entityManager.persist(customer);
            entityManager.flush();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    @Override
    public void assignExecutive(Long custId, String userId) {
        Customer customer = entityManager.find(Customer.class, custId);
        Employee employee = entityManager.find(Employee.class, userId);

        customer.setEmployee(employee);
        customer.setAssigned(Boolean.TRUE);

        entityManager.persist(customer);
        entityManager.flush();
    }

    @Override
    public void unassignCustomers(String userId) {
        Employee employee = entityManager.find(Employee.class, userId);

        for (Customer c : getCustomers()) {
            if (c.getEmployee().getUserId().compareTo(employee.getUserId()) == 0) {
                c.setAssigned(Boolean.FALSE);
                entityManager.persist(c);
                entityManager.flush();
            }
        }
    }

    @Override
    public void tempDeleteCustomer(Long custId) {

        Customer customer = entityManager.find(Customer.class, custId);
        entityManager.remove(customer);

        entityManager.flush();

    }
}
